<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="消息类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择消息类型" clearable>
          <el-option label="文本" :value="1" />
          <el-option label="图片" :value="2" />
          <el-option label="语音" :value="3" />
          <el-option label="视频" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="发送者" prop="from">
        <el-input
          v-model="queryParams.from"
          placeholder="请输入发送者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="接收者" prop="target">
        <el-input
          v-model="queryParams.target"
          placeholder="请输入接收者ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="关键字" prop="searchableKey">
        <el-input
          v-model="queryParams.searchableKey"
          placeholder="请输入搜索关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
  <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="messagesList" @selection-change="handleSelectionChange">
      <el-table-column label="序号" type="index" width="60" align="center" />
      <el-table-column label="消息ID" align="center" prop="mid" width="140" />
      <el-table-column label="消息类型" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <el-tag>
            {{ getMessageTypeText(scope.row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="发送者" align="center" prop="from" width="120" />
      <el-table-column label="接收者" align="center" prop="target" width="120" />
      <el-table-column label="业务线" align="center" prop="line" width="100" />
      <el-table-column label="消息内容" align="left" prop="searchableKey" min-width="250">
        <template slot-scope="scope">
          <div class="message-content">
            {{ scope.row.searchableKey || '无内容' }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="发送时间" align="center" prop="dt" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.dt, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="100">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看消息详情对话框 -->
    <el-dialog title="消息详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="消息ID">{{ viewForm.mid }}</el-descriptions-item>
        <el-descriptions-item label="发送者">{{ viewForm.from }}</el-descriptions-item>
        <el-descriptions-item label="接收者">{{ viewForm.target }}</el-descriptions-item>
        <el-descriptions-item label="消息类型">{{ getMessageTypeText(viewForm.type) }}</el-descriptions-item>
        <el-descriptions-item label="业务线">{{ viewForm.line }}</el-descriptions-item>
        <el-descriptions-item label="发送时间">{{ parseTime(viewForm.dt, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
        <el-descriptions-item label="消息内容" :span="2">
          <div style="max-height: 200px; overflow-y: auto;">
            {{ viewForm.searchableKey || viewForm.data || '无内容' }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 导出用户选择对话框 -->
    <el-dialog title="选择导出用户" :visible.sync="exportDialogOpen" width="400px" append-to-body>
      <el-form :model="exportForm" label-width="80px">
        <el-form-item label="选择用户" required>
          <el-select 
            v-model="exportForm.queryUserId" 
            placeholder="请选择要导出的用户"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="user in userOptions"
              :key="user.uid"
              :label="`${user.displayName}(${user.name})`"
              :value="user.uid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="exportDialogOpen = false">取 消</el-button>
        <el-button type="primary" @click="confirmExport">确认导出</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listMessages } from "@/api/zl/messages"
import { listUser } from "@/api/zl/user"

export default {
  name: "Messages",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 消息表格数据
      messagesList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看对话框
      viewOpen: false,
      // 查看表单
      viewForm: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: null,
        from: null,
        target: null,
        searchableKey: null
      },
      // 导出弹窗
      exportDialogOpen: false,
      exportForm: {
        queryUserId: null
      },
      // 用户列表（如果需要下拉选择）
      userOptions: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询消息列表 */
    getList() {
      this.loading = true
      listMessages(this.queryParams).then(response => {
        this.messagesList = response.rows
        this.total = parseInt(response.total) || 0  // 确保total是数字类型
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.viewForm = { ...row }
      this.viewOpen = true
    },
    /** 获取消息类型文本 */
    getMessageTypeText(type) {
      const typeMap = {
        1: '文本',
        2: '图片', 
        3: '语音',
        4: '视频'
      }
      return typeMap[type] || '未知'
    },
    /** 导出按钮操作 */
    handleExport() {
      // 获取用户列表
      this.getUserList();
      // 打开用户选择弹窗
      this.exportDialogOpen = true;
    },
    
    /** 获取用户列表 */
    getUserList() {
      listUser({ pageNum: 1, pageSize: 20, status: '0' }).then(response => {
        this.userOptions = response.rows || [];
      }).catch(() => {
        this.$modal.msgError('获取用户列表失败');
      });
    },
    
    // 确认导出
    confirmExport() {
      if (!this.exportForm.queryUserId) {
        this.$modal.msgError('请选择要导出的用户');
        return;
      }
      
      this.download('system/messages/export', {
        ...this.queryParams,
        queryUserId: this.exportForm.queryUserId
      }, `messages_${this.exportForm.queryUserId}_${new Date().getTime()}.xlsx`);
      
      this.exportDialogOpen = false;
      this.exportForm.queryUserId = null;
    }
  }
}
</script>

<style scoped>
.message-content {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
